package com.wbdgj.http;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.wbdgj.base.BaseApplication;
import com.wbdgj.utils.LogUtils;
import com.wbdgj.utils.dialog.LoadingDialog;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by CC on 2016/5/28.
 */
public abstract class OnNoResponseListener<T> implements Callback<T> {

//    LoadingDialog dialog;

    private Context context;

    public OnNoResponseListener(Context context) {
        this.context = context;
//        dialog = new LoadingDialog(context);
//        if (needDialog())
//            dialog.show();
    }

    public OnNoResponseListener() {
        this.context = BaseApplication.getInstance();
    }

    protected boolean needDialog() {
        return true;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.code() == 200) {
//            if (response.body() instanceof BaseResultModel) {
//                BaseResultModel commonBean = (BaseResultModel) response.body();
//                if (commonBean.getCode() == 200) {
//                    onSuccess((T) commonBean);
//                } else {
//                    onFailure(commonBean.getMessage());
//                }
//            } else {
//                onSuccess(response.body());
//            }
            onSuccess(response.body());
        } else {
            onFailure(response.code());
            onRequestFailure();
        }

    }

    protected void onRequestFailure() {

    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        String msg = t.getMessage();

        if (TextUtils.isEmpty(msg))
            msg = "请求异常";
        LogUtils.logi(msg);
        onRequestFailure();
    }

    protected void onFailure(int code) {
        Toast.makeText(context, "请求异常:" + code, Toast.LENGTH_SHORT).show();
    }

    protected void onFailure(String msg) {
        Toast.makeText(context, new String(msg), Toast.LENGTH_SHORT).show();
    }

    protected abstract void onSuccess(T t);

    public void dismiss() {

    }

}